<script context="module">
  export async function preload(page, session) {
    if (!session.user) {
      this.error(403, "对不起，请登录之后再查看本页面！");
      return;
    }
    let { p } = page.query;
    if (!p) {
      p = 1;
    }
    p = parseInt(p);
    const perPage = 24;
    const response = await Promise.all([
      this.fetch(`/api2/cash?page=${p}&limit=${perPage}`),
    ]);
    const cash = await response[0].json();
    return { cash: cash.cash, counts: cash.counts, p, perPage };
  }
</script>

<script>
  import { goto, stores } from "@sapper/app";
  import dayjs from "dayjs";
  import relativeTime from "dayjs/plugin/relativeTime";
  import "dayjs/locale/zh-cn";
  import Pagination from "../../components/Pagination.svelte";
  import { toast } from "@zerodevx/svelte-toast";
  import {
    Modal,
    ModalBody,
    ModalFooter,
    ModalHeader
  } from 'sveltestrap/src';
  let open = false;
  const toggle = () => (open = !open);
  let detailOpen = false;
  const detailToggle = () => (detailOpen = !detailOpen);
  dayjs.extend(relativeTime);
  dayjs.locale("zh-cn");
  const { preloading, page, session } = stores();
  let path;
  let selectObj;
  let detailCash;
  $: path = $page.path;
  export let cash;
  export let perPage;
  export let counts;
  export let p;
  async function changePage(evt) {
    const current = evt.detail;
    goto("/cash?p=" + current);
  }
  async function deleteObj(id) {
    const response = await fetch("/api2/cash?id=" + id, {
      method: "DELETE",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    });
    const parsed = await response.json();
    if (parsed.success == 0) {
      toast.push(parsed.message);
    } else {
      toast.push("删除成功，有10分钟缓存，请稍候再查看列表！");
    }
  }
  function openEdit(obj) {
    selectObj= obj;
    open = !open;
  }
  async function detail(obj) {
    detailOpen = !detailOpen;
    const response = await fetch(`/api2/cash?id=${obj._id}`, {
      method: "get",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    }).catch((err) => {
      console.log(err);
    });
    const parsed = await response.json();
    detailCash = parsed.cash;
  }
  async function save() {
    const response = await fetch("/api2/cash", {
      method: "PUT",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify({
        id: selectObj._id,
        amount: selectObj.amount,
        type: selectObj.type,
        description: selectObj.description
      }),
    });
    const parsed = await response.json();
    if (parsed.success == 0) {
      toast.push(parsed.message);
    } else {
      toast.push("编辑成功，因为缓存，可能几分钟之后才能看见修改结果！");
      open=!open;
    }
  }
</script>

<svelte:head>
  <title>支出收入中心 - 记账中心</title>
</svelte:head>
<div class="content">
  <div class="row">
  </div>
  <div class="row mt-4">
    <table class="table table-hover">
      <thead>
        <tr>
          <th scope="col">类型</th>
          <th scope="col">资金</th>
          <th scope="col">备注</th>
          <th scope="col">操作人</th>
          <th scope="col">交易日期</th>
          <th scope="col">操作</th>
        </tr>
      </thead>
      <tbody>
        {#each cash as theCash}
          <tr>
            <td>{theCash.type=='in'?'收入':'支出'}</td>
            <td>{theCash.amount}</td>
            <td>{theCash.description || '无备注'}</td>
            <td>{theCash.creator.name}</td>
            <td>{dayjs(theCash.meta.createAt).format('YYYY-MM-DD HH:mm:ss')}</td>
            <td>
              <div class="btn-group" role="group">
                <button class="btn btn-primary" on:click="{()=>{openEdit(theCash)}}">编辑</button>
                <button class="btn btn-info" on:click="{()=>{detail(theCash)}}">交易明细</button>
                <button class="btn btn-danger" on:click="{()=>{deleteObj(theCash._id)}}">删除</button>
              </div>
            </td>
          </tr>
        {/each}
      </tbody>
    </table>
  </div>
  <div class="d-flex justify-content-center mb-4">
    <Pagination
      rounded
      bind:current={p}
      num_items={counts}
      {perPage}
      on:navigate={changePage}
    />
  </div>
  <Modal isOpen={open} {toggle}>
    <ModalHeader {toggle}>编辑账务</ModalHeader>
    <ModalBody>
      <div class="form-group row">
        <label class="col-sm-2 col-form-label" for="type">类型</label>
        <div class="col-sm-10">
          <div>
            <label class="checkbox-inline m-2">
              <input
                class="types"
                type="radio"
                value='in'
                bind:group={selectObj.type}
              />
              <i class="fas fa-chevron-circle-up"></i> 收入
            </label>
            <label class="checkbox-inline m-2">
              <input
                class="types"
                type="radio"
                value='out'
                bind:group={selectObj.type}
              />
              <i class="fas fa-chevron-circle-down"></i> 支出
            </label>
          </div>
        </div>
      </div>
      <div class="form-group row">
        <label class="col-sm-2 col-form-label" for="amount">金额数</label>
        <div class="col-sm-10">
          <input
            type="number"
            id="amount"
            step="0.01"
            class="form-control"
            placeholder="输入交易金额数"
            bind:value={selectObj.amount}
          />
        </div>
      </div>
      <div class="form-group row">
        <label class="col-sm-2 col-form-label" for="description"
          >交易备注</label
        >
        <div class="col-sm-10">
          <textarea
            id="description"
            class="form-control"
            rows="6"
            placeholder="输入备注，可不填"
            bind:value={selectObj.description}
          />
        </div>
      </div>
    </ModalBody>
    <ModalFooter>
      <button class="btn btn-primary" on:click="{save}">保存</button>
      <button class="btn btn-danger" on:click="{()=>{open=!open}}">关闭</button>
    </ModalFooter>
  </Modal>
  <Modal isOpen={detailOpen} toggle={detailToggle}>
    <ModalHeader toggle={detailToggle}>交易明细</ModalHeader>
    <ModalBody>
      <table class="table table-hover">
        <thead>
          <tr>
            <th scope="col">交易商品</th>
            <th scope="col">商品编号/型号</th>
            <th scope="col">数量</th>
          </tr>
        </thead>
        <tbody>
          {#if detailCash}
          {#if detailCash.exchanges.length==0}
            <p>没有明细</p>
          {/if}
          {#each detailCash.exchanges as exchange}
            <tr>
              <td>{exchange.product.title}</td>
              <td>{exchange.product.pid||'暂无'}</td>
              <td>{exchange.counts}</td>
            </tr>
          {/each}
          {/if}
        </tbody>
      </table>
    </ModalBody>
    <ModalFooter>
      <button class="btn btn-danger" on:click="{()=>{detailOpen=!detailOpen}}">关闭明细</button>
    </ModalFooter>
  </Modal>
</div>
